package com.husd.framework.compile;

import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.util.JavacTask;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.file.JavacFileManager;

import com.sun.tools.javac.util.Context;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author shengdonghu@126.com
 * @date 2022/8/23 14:06
 */
public class ParserByJavac {

    private JavacFileManager fileManager;
    private JavacTool javacTool;

    public ParserByJavac(String sourceFile) {
        Context context = new Context();
        fileManager = new JavacFileManager(context, true, Charset.defaultCharset());
        javacTool = JavacTool.create();
    }
    @SuppressWarnings("all")
    public void parseJava(String sourcePath, TreeVisitor<String, String> treeVisitor) {
        // Java源码文件解析为JavaFileObject
        Iterable<? extends JavaFileObject> files = fileManager.getJavaFileObjects(sourcePath);
        // 创建JavacTask
        JavacTask javacTask = javacTool.getTask(null, fileManager, null, null, null, files);
        try {
            // 构建抽象语法树
            Iterable<? extends CompilationUnitTree> result = javacTask.parse();
            // 使用自定义Visitor遍历抽象语法树
            for (CompilationUnitTree tree : result) {
                tree.accept(treeVisitor, null);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
